<template>
  <div class="applications-page-wrapper">
    <div v-show="!isApplicationDetail">
      <div :style="{ display: 'flex', justifyContent: 'end', marginBottom: '10px' }">
        <el-button type="primary">新建应用</el-button>
      </div>
      <el-table :data="applications" style="width: 100%">
        <el-table-column prop="name" label="应用名称">
          <template #default="scope">
            <el-button type="primary" link @click="onClickApplication(scope.row.id)">
              {{ scope.row.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="应用类型">
          <template #default="scope">
            <el-tag v-if="scope.row.type == 'client'" type="success">前端</el-tag>
            <el-tag v-else type="primary">后端</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="应用描述" />
      </el-table>
    </div>
    <div v-show="isApplicationDetail"><router-view /></div>
  </div>
</template>

<script lang="ts" setup>
import { useApplicationService } from '@/service/application-service';
import { useSystemService } from '@/service/system-service';
import { Application } from '@/store/application-repository';
import { System } from '@/store/system-repository';

const router = useRouter();
const route = useRoute();
const systemService = useSystemService();
const applicationService = useApplicationService();

const projectId = computed(() => {
  return route.params.projectId as string;
});
const systemId = computed(() => {
  return route.params.systemId as string;
});

const isApplicationDetail = computed(() => {
  return route.name == 'ApplicationDetail';
});

const system = ref<System>();
// 系统中的应用
const applications = ref<Array<Application>>([]);
watch(
  systemId,
  newSystemId => {
    systemService.system(newSystemId).then(data => {
      system.value = data;
      loadApplications(newSystemId);
    });
  },
  { immediate: true },
);
const loadApplications = (systemId: string) => {
  applicationService.applications(systemId).then(data => {
    applications.value = data.records ?? [];
  });
};

const onClickApplication = (applicationId: string) => {
  router.push({
    name: 'ApplicationDetail',
    params: { projectId: projectId.value, systemId: systemId.value, applicationId },
  });
};
</script>
